Passed
Push — master ( dd4450...9a9614 )
by Andrey
05:55
created

custom.js ➔ showAlert   B

Complexity

Conditions 7

Size

Total Lines 27
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 19
c 0
b 0
f 0
dl 0
loc 27
rs 8
1
2
// ISOTOPE FILTER
3
jQuery(document).ready(function($){
4
5
  if ( $('.iso-box-wrapper').length > 0 ) { 
6
7
      var $container  = $('.iso-box-wrapper'), 
8
        $imgs     = $('.iso-box img');
9
10
      $container.imagesLoaded(function () {
11
12
        $container.isotope({
13
        layoutMode: 'fitRows',
14
        itemSelector: '.iso-box'
15
        });
16
17
        $imgs.load(function(){
18
          $container.isotope('reLayout');
19
        })
20
21
      });
22
23
      //filter items on button click
24
25
      $('.filter-wrapper li a').click(function(){
26
27
          var $this = $(this), filterValue = $this.attr('data-filter');
28
29
      $container.isotope({ 
30
        filter: filterValue,
31
        animationOptions: { 
32
            duration: 750, 
33
            easing: 'linear', 
34
            queue: false, 
35
        }                
36
      });             
37
38
      // don't proceed if already selected 
39
40
      if ( $this.hasClass('selected') ) { 
41
        return false; 
42
      }
43
44
      var filter_wrapper = $this.closest('.filter-wrapper');
45
      filter_wrapper.find('.selected').removeClass('selected');
46
      $this.addClass('selected');
47
48
        return false;
49
      }); 
50
51
  }
52
53
});
54
55
// jQuery to collapse the navbar on scroll //
56
$(window).scroll(function() {
57
    if ($(".navbar").offset().top > 50) {
58
        $(".navbar-fixed-top").addClass("top-nav-collapse");
59
    } else {
60
        $(".navbar-fixed-top").removeClass("top-nav-collapse");
61
    }
62
});
63
64
/* HTML document is loaded. DOM is ready. 
65
-------------------------------------------*/
66
$(function(){
67
68
  // ------- WOW ANIMATED ------ //
69
  wow = new WOW(
0 ignored issues
show
Bug introduced by
The variable WOW seems to be never declared. If this is a global, consider adding a /** global: WOW */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
Bug introduced by
The variable wow seems to be never declared. Assigning variables without defining them first makes them global. If this was intended, consider making it explicit like using window.wow.
Loading history...
70
  {
71
    mobile: false
72
  });
73
  wow.init();
74
75
  // HIDE MOBILE MENU AFTER CLIKING ON A LINK
76
  $('.navbar-collapse a').click(function(){
77
        $(".navbar-collapse").collapse('hide');
78
    });
79
80
  // NIVO LIGHTBOX
81
  $('.iso-box-section a').nivoLightbox({
82
        effect: 'fadeScale',
83
    });
84
85
});
86
87
/**
88
 * Serialize object to string.
89
 *
90
 * @param   {object} obj    - Object incoming
91
 * @returns {string}        - Object as Get params string
92
 */
93
function serializeParams(obj) {
94
    return Object.keys(obj).reduce(function(a,k) {a.push(k+'='+encodeURIComponent(obj[k]));return a},[]).join('&');
95
}
96
97
/**
98
 * AJAX function.
99
 *
100
 * @param {string} url     - Request URL
101
 * @param {string} method  - Request type ('post' || 'get')
102
 * @param {object} params  - Object with params (for files { name: 'sasha' (sended to $_POST[]), files: { custom_filename: element.files[0] } (sended to $_FILES[]))
103
 * @param {object} options - Object with options. Available options:
104
 *     response_json{bool} - Type of response (JSON or not)
105
 *     func_waiting{func}  - Function while waiting
106
 *     func_callback{func} - Function on success result
107
 *     func_error{func}    - Function on error result
108
 *     func_progress{func} - Function on uploading progress
109
 */
110
function AJAX(url, method, params, options) {
111
    var xhr = null;
112
113
    try { // For: chrome, firefox, safari, opera, yandex, ...
114
        xhr = new XMLHttpRequest();
115
    } catch(e) {
116
        try { // For: IE6+
117
            xhr = new ActiveXObject("Microsoft.XMLHTTP");
0 ignored issues
show
Bug introduced by
The variable ActiveXObject seems to be never declared. If this is a global, consider adding a /** global: ActiveXObject */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
118
        } catch(e1) { // if JS not supported or disabled
119
            console.log("Browser Not supported!");
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
120
            return;
121
        }
122
    }
123
124
    xhr.onreadystatechange = function() {
125
126
        // ready states:
127
        // 0: uninitialized
128
        // 1: loading
129
        // 2: loaded
130
        // 3: interactive
131
        // 4: complete
132
133
        if (xhr.readyState == 4) { // when result is ready
134
135
            var response_text = xhr.responseText;
136
137
            if ('response_json' in options && options.response_json) {
138
                try {
139
                    response_text = JSON.parse(response_text);
140
                } catch (e) { }
0 ignored issues
show
Coding Style Comprehensibility Best Practice introduced by
Empty catch clauses should be used with caution; consider adding a comment why this is needed.
Loading history...
141
            }
142
143
            if (xhr.status === 200) { // on success
144
                if ('func_callback' in options && typeof options.func_callback == 'function') {
145
                    var fc = options.func_callback;
146
                    fc(response_text);
147
                }
148
            } else { // on error
149
                console.log(xhr.status + ': ' + xhr.statusText);
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
150
                if ('func_error' in options && typeof options.func_error == 'function') {
151
                    var fe = options.func_error;
152
                    fe(response_text, xhr);
153
                }
154
            }
155
        } else { // waiting for result
156
            if ('func_waiting' in options && typeof options.func_waiting == 'function') {
157
                var fw = options.func_waiting;
158
                fw();
159
            }
160
        }
161
    };
162
163
    var data = null;
0 ignored issues
show
Unused Code introduced by
The assignment to data seems to be never used. If you intend to free memory here, this is not necessary since the variable leaves the scope anyway.
Loading history...
164
165
    if (params.files) {
166
        method = 'POST';
167
168
        data = new FormData();
169
        for (var index_param in params) {
0 ignored issues
show
Complexity introduced by
A for in loop automatically includes the property of any prototype object, consider checking the key using hasOwnProperty.

When iterating over the keys of an object, this includes not only the keys of the object, but also keys contained in the prototype of that object. It is generally a best practice to check for these keys specifically:

var someObject;
for (var key in someObject) {
    if ( ! someObject.hasOwnProperty(key)) {
        continue; // Skip keys from the prototype.
    }

    doSomethingWith(key);
}
Loading history...
170
            if (typeof params[index_param] == 'object') {
171
                for (var index_file in params[index_param]) {
0 ignored issues
show
Complexity introduced by
A for in loop automatically includes the property of any prototype object, consider checking the key using hasOwnProperty.

When iterating over the keys of an object, this includes not only the keys of the object, but also keys contained in the prototype of that object. It is generally a best practice to check for these keys specifically:

var someObject;
for (var key in someObject) {
    if ( ! someObject.hasOwnProperty(key)) {
        continue; // Skip keys from the prototype.
    }

    doSomethingWith(key);
}
Loading history...
172
                    data.append(index_file, params[index_param][index_file]);
173
                }
174
            } else {
175
                data.append(index_param, params[index_param]);
176
            }
177
        }
178
179
        if ('func_progress' in options && typeof options.func_progress == 'function') {
180
            xhr.upload.onprogress = function(event) {
181
                // 'progress: ' + event.loaded + ' / ' + event.total;
182
                var fp = options.func_progress;
183
                fp(event);
184
            }
185
        }
186
    } else {
187
        data = serializeParams(params);
188
    }
189
190
    method = method.toUpperCase();
191
192
    if (method == 'GET' && data) {
193
        url += '?' + data;
194
    }
195
196
    xhr.open(method, url, true);
197
198
    if ( ! params.files) {
199
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
200
    }
201
202
    xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
203
    xhr.send(data);
204
}
205
206
/**
207
 * Add cross browser event to DOM element
208
 *
209
 * @param {object} element			- Element for adding event
210
 * @param {string} event_name   	- Event name
211
 * @param {function} event_handler	- Event handler
212
 */
213
function addEvent(element, event_name, event_handler) {
214
    if (event_name == 'ready') {
215
        if (document.addEventListener) {
216
            document.addEventListener("DOMContentLoaded", event_handler, false);
217
        } else if (document.attachEvent) {
218
            document.attachEvent("onreadystatechange", function() {
219
                if (document.readyState === "complete" ) {
220
                    event_handler();
221
                }
222
            });
223
        }
224
    } else {
225
        if (element.addEventListener) {
226
            element.addEventListener(event_name, event_handler, false);
227
        } else if (element.attachEvent) {
228
            element.attachEvent('on' + event_name, event_handler);
229
        }
230
    }
231
}
232
233
/**
234
 * @param {element} parentBlock
235
 * @param {string} textAlert
236
 * @param {string} status
237
 *      success
238
 *      info
239
 *      warning
240
 *      danger
241
 */
242
function showAlert(parentBlock, textAlert, status) {
243
    var possibleStatuses = [
244
        'success',
245
        'info',
246
        'warning',
247
        'danger'
248
    ];
249
    var alertBlock = parentBlock.find('[role="alert"]');
250
    if (alertBlock.hasClass('hidden')) {
251
        alertBlock.removeClass('hidden');
252
    }
253
    if (!alertBlock.hasClass('show')) {
254
        alertBlock.addClass('show');
255
    }
256
    for (var i = 0; i < possibleStatuses.length; i++) {
257
        if (status != possibleStatuses[i]) {
258
            if (alertBlock.hasClass('alert-'+possibleStatuses[i])) {
259
                alertBlock.removeClass('alert-'+possibleStatuses[i]);
260
            }
261
        } else {
262
            if (!alertBlock.hasClass('alert-'+status)) {
263
                alertBlock.addClass('alert-'+status);
264
            }
265
        }
266
    }
267
    alertBlock.text(textAlert);
268
}
269
270
/**
271
 * @param parentBlock
272
 */
273
function closeAlert(parentBlock) {
274
    var possibleStatuses = [
275
        'success',
276
        'info',
277
        'warning',
278
        'danger'
279
    ];
280
    var alertBlock = parentBlock.find('[role="alert"]');
281
    if (alertBlock.hasClass('show')) {
282
        alertBlock.removeClass('show');
283
    }
284
    if (!alertBlock.hasClass('hidden')) {
285
        alertBlock.addClass('hidden');
286
    }
287
    for (var i = 0; i < possibleStatuses.length; i++) {
288
        if (alertBlock.hasClass('alert-'+possibleStatuses[i])) {
289
            alertBlock.removeClass('alert-'+possibleStatuses[i]);
290
        }
291
    }
292
    alertBlock.text('');
293
}
294
295
// CAPTCHA
296
297
var recaptcha_status = 'passive';
298
299
function grecaptcha_reset() {
300
    grecaptcha.reset();
0 ignored issues
show
Bug introduced by
The variable grecaptcha seems to be never declared. If this is a global, consider adding a /** global: grecaptcha */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
301
}
302
303
function grecaptcha_execute() {
304
    grecaptcha.execute();
0 ignored issues
show
Bug introduced by
The variable grecaptcha seems to be never declared. If this is a global, consider adding a /** global: grecaptcha */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
305
}
306
307
/**
308
 * Validate recaptcha, using ajax request to the google recaptcha service.
309
 *
310
 * @param callbacks
311
 *     func_waiting{func}  - Function while waiting
312
 *     func_callback_success{func} - Function on success result with status 200
313
 *     func_callback_error{Func} - Function on error result with status 200
314
 */
315
function validateRecaptcha(callbacks) {
316
    var url = "/ajax/recaptcha-ajax/validate";
317
    var params = {
318
        _csrf: window.yii.getCsrfToken(),
319
        g_recaptcha_response: grecaptcha.getResponse()
0 ignored issues
show
Bug introduced by
The variable grecaptcha seems to be never declared. If this is a global, consider adding a /** global: grecaptcha */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
320
    };
321
    AJAX(url, 'POST', params, {
322
        response_json: true,
323
        func_waiting: function () {
324
            if ('func_waiting' in callbacks && typeof callbacks.func_waiting == 'function') {
325
                var fw = callbacks.func_waiting;
326
                fw();
327
            }
328
        },
329
        func_callback: function (resp) {
330
            if (resp.meta.status == 'success') {
331
                if ('func_callback_success' in callbacks && typeof callbacks.func_callback_success == 'function') {
332
                    var fcs = callbacks.func_callback_success;
333
                    fcs(resp);
334
                }
335
            } else if (resp.meta.status == 'fail') {
336
                if ('func_callback_error' in callbacks && typeof callbacks.func_callback_error == 'function') {
337
                    var fce = callbacks.func_callback_error;
338
                    fce(resp);
339
                }
340
                grecaptcha_reset();
341
            }
342
        },
343
        func_error: function (resp, xhr) {
0 ignored issues
show
Unused Code introduced by
The parameter resp is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
Unused Code introduced by
The parameter xhr is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
344
            grecaptcha_reset();
345
        }
346
    });
347
}
348